/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package persistence;

import Utility.VarcharUpdater;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import logging.CommonsLogging;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import vo.rb_purchase;

/**
 *
 * @author Shuhail
 */
public class rb_purchase_persist {
    
    Session sess=null;
    Transaction tx=null;
    Logger logger = CommonsLogging.getInstance().getLogger();
    
    public static rb_purchase_persist getInstance() {
        
        return new rb_purchase_persist();
    }
    
    public rb_purchase_persist() {
        
        SessionFactory sf = new Configuration().configure().buildSessionFactory();
        sess=sf.openSession();
        tx=sess.beginTransaction();
        
    }
    
    public List<rb_purchase> fetchAll() {
        List<rb_purchase> list = null;
        
        Query query = sess.getNamedQuery("getAllPurchase");
        list = query.list();
        return list;
        
    }
    
    
    public String getLastPK() {
        List<rb_purchase> purchase = new ArrayList<rb_purchase>();
        purchase = this.fetchAll();
        Iterator it = purchase.iterator();
        List<String> list = new ArrayList<String>();
        while(it.hasNext()) {
            rb_purchase pur = (rb_purchase)it.next();
            list.add(pur.getPurchase_invoice_no());
        }
        String last_pk = VarcharUpdater.getInstance().getTheLastPK(list);
        return last_pk;
    }
    public boolean insertIntoPurchase(rb_purchase purchase) {
        
        String next_pk = VarcharUpdater.getInstance().getValue(this.getLastPK());
        if(logger.isDebugEnabled())
            logger.debug("Next Primary key generated:::"+next_pk);
        tx.begin();
        purchase.setPurchase_invoice_no(next_pk);
        try {
            
            sess.save(purchase);
            tx.commit();
            return true;
            
        }
        catch(Exception e) {
        return false;
        }
    }
}
